﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyVoteMVC.Service;
using MyVoteMVC.Domain;
using MyVoteMVC.Common;
using MyVoteMVC.Web.Extensions;
using MyVoteMVC.Web.Models;
using Telerik.Web.Mvc;
using System.IO;
using System.Web.Security;


namespace MyVoteMVC.Web.Controllers
{
    public class HomeController : VoteBaseController
    {
        [Authorize]
        public ActionResult Index()
        {            
            using (IActivityService pService = Factory.GetInstance<IActivityService>())
            {
                //读取用户身份
                FormsIdentity pIdentity = (FormsIdentity)HttpContext.User.Identity;
                FormsAuthenticationTicket pTicket = pIdentity.Ticket;

                ActivityConverter pConverter = new ActivityConverter();
                var pList = pService.GetNowActivitiesList(pTicket.UserData);
                var pResult = pList.ToModelList<VT_Activities, Activity>(pConverter);
                foreach (var pCR in pResult)
                {
                    pCR.CurrentState = "活动进行中";
                }

                var pHistoryList = pService.GetHistoryActivitiesList(pTicket.UserData);
                var pHistoryResult = pHistoryList.ToModelList<VT_Activities, Activity>(pConverter);
                foreach (var pHR in pHistoryResult)
                {
                    pHR.CurrentState = "活动已结束";
                    pResult.Add(pHR);
                }
                return View(pResult);
            }
            //return View();
        }

        public ActionResult About()
        {
            return View();
        }

        [Authorize]
        public ActionResult MyActivity()
        {
            //读取用户身份
            FormsIdentity pIdentity = (FormsIdentity)HttpContext.User.Identity;
            FormsAuthenticationTicket pTicket = pIdentity.Ticket;

            using (IActivityService pService = Factory.GetInstance<IActivityService>())
            {
                ActivityConverter pConverter = new ActivityConverter();
                var pList = pService.GetUserNowActivitiesList(pTicket.UserData, DateTime.Now);
                var pResult = pList.ToModelList<VT_Activities, Activity>(pConverter);
                foreach (var pCR in pResult)
                {
                    pCR.CurrentState = "活动进行中";
                }

                var pHistoryList = pService.GetUserHistoryActivitiesList(pTicket.UserData, DateTime.Now);
                var pHistoryResult = pHistoryList.ToModelList<VT_Activities, Activity>(pConverter);
                foreach (var pHR in pHistoryResult)
                {
                    pHR.CurrentState = "活动已结束";
                    pResult.Add(pHR);
                }
                return View(pResult);
            }
        }

        [GridAction]
        public ActionResult _ActivityAjaxBinding()
        {
            using (IActivityService pService = Factory.GetInstance<IActivityService>())
            {
                ActivityConverter pConverter = new ActivityConverter();
                var pList = pService.GetActivitiesList(DateTime.Now);
                var pResult = pList.ToModelList<VT_Activities, Activity>(pConverter);
                foreach (var pCR in pResult)
                {
                    pCR.CurrentState = "活动进行中";
                }

                var pHistoryList = pService.GetHistoryActivitiesList(DateTime.Now);
                var pHistoryResult = pHistoryList.ToModelList<VT_Activities, Activity>(pConverter);
                foreach (var pHR in pHistoryResult)
                {
                    pHR.CurrentState = "活动已结束";
                    pResult.Add(pHR);
                }
                return View(new GridModel(pResult));
            }
        }

       
        [GridAction]
        public ActionResult _MyActivityAjaxBinding()
        {
            //读取用户身份
            FormsIdentity pIdentity = (FormsIdentity)HttpContext.User.Identity;
            FormsAuthenticationTicket pTicket = pIdentity.Ticket;

            using (IActivityService pService = Factory.GetInstance<IActivityService>())
            {
                ActivityConverter pConverter = new ActivityConverter();
                var pList = pService.GetUserNowActivitiesList(pTicket.UserData,DateTime.Now);
                var pResult = pList.ToModelList<VT_Activities, Activity>(pConverter);
                foreach (var pCR in pResult)
                {
                    pCR.CurrentState = "活动进行中";
                }

                var pHistoryList = pService.GetUserHistoryActivitiesList(pTicket.UserData,DateTime.Now);
                var pHistoryResult = pHistoryList.ToModelList<VT_Activities, Activity>(pConverter);
                foreach (var pHR in pHistoryResult)
                {
                    pHR.CurrentState = "活动已结束";
                    pResult.Add(pHR);
                }
                return View(new GridModel(pResult));
            }
        }

        [Authorize]
        public ActionResult Details(string id)
        {
            using (IActivityService pService = Factory.GetInstance<IActivityService>())
            {
                var pActivity = pService.GetActivities(id);
                pService.AddActivityViewCount(id);
                if (pActivity.Activity_IfReadAll.HasValue && pActivity.Activity_IfReadAll.Value > 0)
                    return RedirectToAction("ProjectDetails", new { id = id });
                else
                    return RedirectToAction("ItemDetails", new { id = id });
            }

        }
        [Authorize]
        public ActionResult ItemDetails(string id)
        {
            //读取用户身份
            FormsIdentity pIdentity = (FormsIdentity)HttpContext.User.Identity;
            FormsAuthenticationTicket pTicket = pIdentity.Ticket;
            
            ViewData["ticketSubmit"] = true;
            string pVoteTicket = string.Empty;

            //读取已保存票据信息
            using (ITickService pTickService = Factory.GetInstance<ITickService>())
            {
                pVoteTicket = pTickService.GetContent(id, pTicket.UserData);
                if (pVoteTicket != null)
                {
                    var pVoteTicketGroup = pVoteTicket.Split('&');

                    List<string> finalResult = new List<string>();

                    foreach (string subgroup in pVoteTicketGroup)
                    {
                        finalResult.Add(subgroup.Split('=')[1]);
                    }

                    ViewData["checkedRecords"] = finalResult.ToArray();
                    //检查票据状态
                    ViewData["ticketSubmit"] = pTickService.IsCanModify(id, pTicket.UserData);
                }
            }

            //读取活动相关信息
            using (IActivityService pService = Factory.GetInstance<IActivityService>())
            {
                //定义Item转换
                ItemConverter pConverter = new ItemConverter();

                //读取活动信息
                var pActivity = pService.GetActivities(id);
                var pQuestionList = pActivity.Questions;
                var pResult = new List<Item>();
                if (pActivity.Activity_EndTime < DateTime.Now)
                    ViewData["ticketSubmit"] = false;
                foreach (VT_Questions pQuestion in pQuestionList)
                {
                    //Item列表转换
                    var pItemList = pQuestion.Items.ToModelList<VT_Items, Item>(pConverter);

                    //之前没有提交过票据，则根据默认值勾选
                    if (string.IsNullOrEmpty(pVoteTicket))
                    {
                        ViewData["checkedRecords"] = pItemList.Where(o => o.IfDefault == 1).Select(o => o.ID).ToArray();
                    }
                    pResult.AddRange(pItemList);
                }

                return View("Details",pResult);
            }
        }

        [Authorize]
        public ActionResult ProjectDetails(string id)
        {
            //读取用户身份
            FormsIdentity pIdentity = (FormsIdentity)HttpContext.User.Identity;
            FormsAuthenticationTicket pTicket = pIdentity.Ticket;
            
            ViewData["ticketSubmit"] = true;
            string pVoteTicket = string.Empty;

            //读取已保存票据信息
            using (ITickService pTickService = Factory.GetInstance<ITickService>())
            {
                pVoteTicket = pTickService.GetContent(id, pTicket.UserData);
                if (pVoteTicket != null)
                {
                    var pVoteTicketGroup = pVoteTicket.Split('&');
                    
                    List<string> finalResult = new List<string>();

                    foreach(string subgroup in pVoteTicketGroup)
                    {
                        finalResult.Add(subgroup.Split('=')[1]);
                    }

                    ViewData["checkedRecords"] = finalResult.ToArray();
                    //检查票据状态
                    ViewData["ticketSubmit"] = pTickService.IsCanModify(id, pTicket.UserData);
                }
            }

            //读取活动相关信息
            using (IActivityService pService = Factory.GetInstance<IActivityService>())
            {
                //定义Item转换
                ItemConverter pConverter = new ItemConverter();

                //读取活动信息
                var pActivity = pService.GetActivities(id);
                if (!string.IsNullOrWhiteSpace(pActivity.Activity_PID))
                    ViewData["showStatistics"] = false;
                else
                    ViewData["showStatistics"] = true;


                var pQuestionList = pActivity.Questions;
                var pResult = new List<Item>();
                if (pActivity.Activity_EndTime < DateTime.Now)
                    ViewData["ticketSubmit"] = false;

                using (IProjectService pProjectService = Factory.GetInstance<IProjectService>()) 
                {
                    ViewData["typeList"] = pProjectService.GetProjectsTypeByActivity(id);
                    ViewData["yearList"] = pProjectService.GetProjectsYearGroupByActivity(id);
                }
                foreach (VT_Questions pQuestion in pQuestionList)
                {
                    //Item列表转换
                    var pItemList = pQuestion.Items.ToModelList<VT_Items, Item>(pConverter);

                    //之前没有提交过票据，则根据默认值勾选
                    if (string.IsNullOrEmpty(pVoteTicket))
                    {
                        ViewData["checkedRecords"] = pItemList.Where(o => o.IfDefault == 1).Select(o => o.ID).ToArray();
                    }
                    pResult.AddRange(pItemList);
                }

                return View(pResult);
            }
        }

        public ActionResult ProjectQuestions(string id)
        {
            using (IQuestionService pService = Factory.GetInstance<IQuestionService>())
            {
                var pResult = pService.GetQuestions(id);
                return View(pResult);
            }  
        }
        
        [Authorize]
        [HttpPost]
        public ActionResult Save(string id)
        {
            //读取用户身份
            FormsIdentity pIdentity = (FormsIdentity)HttpContext.User.Identity;
            FormsAuthenticationTicket pTicket = pIdentity.Ticket;
            
            //ViewData["ticketSubmit"] = true;//使用保存功能不影响提交按钮

            //保存票据信息
            using (ITickService pTickService = Factory.GetInstance<ITickService>())
            {
                //判断是否勾选
                if (Request.Form.Count > 0)
                {
                    //保存票据
                    if (!SubmitChecker.SubmitFreCheck())
                    {
                        var pVoteTicket = pTickService.Save(id, pTicket.UserData, Request.Form.ToString(), pTicket.Name);
                        SubmitChecker.SetLastSubmitDate();
                    }
                }
            }

            using (IActivityService pService = Factory.GetInstance<IActivityService>())
            {
                var pActivity = pService.GetActivityByIdWhenAdmin(id);
                if (pActivity.Activity_IfReadAll.HasValue && pActivity.Activity_IfReadAll.Value > 0)
                    return RedirectToAction("ProjectDetails", new { id=id});
                else
                    return RedirectToAction("ItemDetails", new { id=id});
            }

            ////读取活动相关信息
            //using (IActivityService pService = Factory.GetInstance<IActivityService>())
            //{
            //    ItemConverter pConverter = new ItemConverter();

            //    var pActivity = pService.GetActivityByIdWhenAdmin(id);
            //    var pQuestionList = pActivity.Questions;
            //    var pResult = new List<Item>();

            //    if (pActivity.Activity_EndTime < DateTime.Now)
            //        ViewData["ticketSubmit"] = false;

            //    foreach (VT_Questions pQuestion in pQuestionList)
            //    {
            //        var pItemList = pQuestion.Items.ToModelList<VT_Items, Item>(pConverter);
            //        pResult.AddRange(pItemList);
            //    }

            //    if (pActivity.Activity_IfReadAll.HasValue && pActivity.Activity_IfReadAll.Value > 0)
            //        return View("ProjectDetails",pResult);
            //    else
            //        return View("Details",pResult);
            //}
        }

        [Authorize]
        [HttpPost]
        public ActionResult Submit(string id)
        {
            //读取用户身份
            FormsIdentity pIdentity = (FormsIdentity)HttpContext.User.Identity;
            FormsAuthenticationTicket pTicket = pIdentity.Ticket;
            
            //ViewData["ticketSubmit"] = false;
            

            //初始化checkbox与button可视化
            using (ITickService pTickService = Factory.GetInstance<ITickService>())
            {
                //判断是否勾选
                if (Request.Form.Count > 0)
                {
                    //检查
                    foreach (var pQuestionId in Request.Form.AllKeys)
                    {
                        using (IQuestionService pQuestionService = Factory.GetInstance<IQuestionService>())
                        {
                            var pQuestion = pQuestionService.GetQuestion(pQuestionId);
                            var ItemCount = Request.Form[pQuestionId].Split(',').Count();
                            if (ItemCount != pQuestion.MultiCount)
                            {
                                ModelState.AddModelError("", "您现在选择了" + ItemCount +
                                    "项，请确保选择" + pQuestion.MultiCount + "项。");
                                TempData["ModelErrorMsg"] = "您现在选择了" + ItemCount +
                                    "项，请确保选择" + pQuestion.MultiCount + "项。";

                                if (pQuestion.Activity.Activity_IfReadAll.HasValue && pQuestion.Activity.Activity_IfReadAll.Value > 0)
                                    return RedirectToAction("ProjectDetails", new { id = id });
                                else
                                    return RedirectToAction("ItemDetails", new { id = id });
                            }
                        }
                    }
                    //提交票据
                    if (!SubmitChecker.SubmitFreCheck())
                    {
                        var pVoteTicket = pTickService.Submit(id, pTicket.UserData, Request.Form.ToString(), pTicket.Name);
                        SubmitChecker.SetLastSubmitDate();
                    }                    
                }
            }

            using (IActivityService pService = Factory.GetInstance<IActivityService>())
            {
                var pActivity = pService.GetActivityByIdWhenAdmin(id);
                if (pActivity.Activity_IfReadAll.HasValue && pActivity.Activity_IfReadAll.Value > 0)
                    return RedirectToAction("ProjectDetails", new { id = id });
                else
                    return RedirectToAction("ItemDetails", new { id = id });
            }

            ////读取活动相关信息
            //using (IActivityService pService = Factory.GetInstance<IActivityService>())
            //{
            //    ItemConverter pConverter = new ItemConverter();

            //    var pActivity = pService.GetActivityByIdWhenAdmin(id);
            //    var pQuestionList = pActivity.Questions;
            //    var pResult = new List<Item>();

            //    if (pActivity.Activity_EndTime < DateTime.Now)
            //        ViewData["ticketSubmit"] = false;

            //    foreach (VT_Questions pQuestion in pQuestionList)
            //    {
            //        var pItemList = pQuestion.Items.ToModelList<VT_Items, Item>(pConverter);
            //        pResult.AddRange(pItemList);
            //    }

            //    if (pActivity.Activity_IfReadAll.HasValue && pActivity.Activity_IfReadAll.Value > 0)
            //        return View("ProjectDetails", pResult);
            //    else
            //        return View("Details", pResult);
            //}
        }

        [Authorize]
        public ActionResult ViewResult(string id)
        {
            //读取用户身份
            FormsIdentity pIdentity = (FormsIdentity)HttpContext.User.Identity;
            FormsAuthenticationTicket pTicket = pIdentity.Ticket;
            
            //读取活动相关信息
            using (IActivityService pService = Factory.GetInstance<IActivityService>())
            {
                ////定义Item转换
                //StatConverter pConverter = new StatConverter();

                ////读取活动信息
                //var pActivity = pService.GetActivityByIdWhenAdmin(id);
                //var pQuestionList = pActivity.Questions;
                //var pResult = new List<Stat>();
                //if (pActivity.Activity_EndTime < DateTime.Now)
                //    ViewData["ticketSubmit"] = false;
                //foreach (VT_Questions pQuestion in pQuestionList)
                //{
                //    //Item列表转换
                //    var pItemList = pQuestion.Items.ToModelList<VT_Items, Stat>(pConverter);
                    
                //    pResult.AddRange(pItemList);
                //}                

                var pResult = new List<Stat>();
                for (int i=0;i<300;i++){
                    pResult.Add(new Stat
                    {
                        Offline_Count = 2,
                        Online_Count = 3,
                        QID = "1",
                        QNO = "2",
                        QTitle = "3",
                        Title = i.ToString()
                    });
                }
                
                return View(pResult);
            }
        }

        [Authorize]
        public ActionResult VoteResult(string id)
        {
            using (IQuestionService pService = Factory.GetInstance<IQuestionService>())
            {
                var pResult = pService.GetQuestions(id);
                return View(pResult);
            }            
        }

        [Authorize]
        public ActionResult VoteQuestion(string id)
        {
            //读取用户身份
            FormsIdentity pIdentity = (FormsIdentity)HttpContext.User.Identity;
            FormsAuthenticationTicket pTicket = pIdentity.Ticket;

            using (IQuestionService pService = Factory.GetInstance<IQuestionService>())
            {
                StatConverter pConverter = new StatConverter();

                var pQuestion = pService.GetQuestion(id);
                ViewData["QuestionNo"] = pQuestion.Question_No.ToString();
                ViewData["QuestionTitle"] = pQuestion.Question_Title;
                var pResult = new List<Stat>();
                pResult = pQuestion.Items.OrderByDescending(o => (o.Offline_Count + o.Online_Count)).ToModelList<VT_Items, Stat>(pConverter).ToList();
                using(IUserService pUserService = Factory.GetInstance<IUserService>())
                {
                    using (IActivityService pActivityService = Factory.GetInstance<IActivityService>())
                    {
                        if (pUserService.CheckLeader(pTicket.UserData) || pUserService.CheckAdmin(pTicket.UserData))
                            return PartialView("VoteResultControl", pResult);
                        else if (!pActivityService.CheckActivity(pQuestion.Activity_ID))
                            pResult = pResult.Take(10).ToList();

                    }
                }
                return PartialView("VoteResultControl", pResult);
            }
        }

        public ActionResult _VoteResult(string id)
        {
            using (IQuestionService pService = Factory.GetInstance<IQuestionService>())
            {
                StatConverter pConverter = new StatConverter();

                var pQuestion = pService.GetQuestion(id);
                var pResult = new List<Stat>();

                pResult = pQuestion.Items.ToModelList<VT_Items, Stat>(pConverter).ToList();
                return Json(pResult);
            } 
            
            //for (int i = 0; i < 300; i++)
            //{
            //    pResult.Add(new Stat
            //    {
            //        Offline_Count = 2,
            //        Online_Count = 3,
            //        QID = "1",
            //        QNO = "2",
            //        QTitle = "3",
            //        Title = i.ToString()
            //    });
            //}
            //return Json(pResult);
        }

        public ActionResult RefreshMessageById(string id, int? span)
        {
            using (IMessageService pService = Factory.GetInstance<IMessageService>())
            {
                if (span.HasValue)
                {
                    var list = pService.GetMessageListByInterval(id, span.Value)
                        .ToModelList<VT_Messages, Message>(new MessageConverter());
                    return Json(list, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    var list = pService.GetMessageList(id)
                       .ToModelList<VT_Messages, Message>(new MessageConverter());
                    return Json(list, JsonRequestBehavior.AllowGet);
                }
            }
        }

        public ActionResult RefreshMessage(int? span)
        {
            using (IMessageService pService = Factory.GetInstance<IMessageService>())
            {
                if (span.HasValue)
                {
                    var list = pService.GetMessageListByInterval(span.Value)
                        .ToModelList<VT_Messages, Message>(new MessageConverter());
                    return Json(list, JsonRequestBehavior.AllowGet);
                }

                else
                {
                    var list = pService.GetMessageList()
                       .ToModelList<VT_Messages, Message>(new MessageConverter());
                    return Json(list, JsonRequestBehavior.AllowGet);
                }

            }
        }

        public JsonResult AddMessage(Message message)
        {
            using (IMessageService pService = Factory.GetInstance<IMessageService>())
            {
                try
                {
                    //读取用户身份
                    FormsIdentity pIdentity = (FormsIdentity)HttpContext.User.Identity;
                    FormsAuthenticationTicket pTicket = pIdentity.Ticket;
                    string messageid="";
                    if (pService.CreateMessage(
                        message.Activity_ID,
                        message.Title,
                        message.Content,
                        pTicket.Name,out messageid))
                    {
                        return Json(new { message = "发送成功", name = pTicket.Name, ID = messageid, Date = DateTime.Now.ToString() });
                    }
                    else
                    {
                        return Json(new { message = "发送失败" });
                    }
                }
                catch
                {
                    return Json(new { message = "系统出错，请联系管理员。" });
                }
            }
        }


        public ActionResult ProjectById(string id)
        {
            using (IProjectService pService = Factory.GetInstance<IProjectService>())
            {
                var project = new ProjectConverter()
                    .Convert(pService.GetProjectById(id));
                return PartialView("ProjectInfoControl", project);
            }

        }

        public ActionResult ProjectByItemId(string id)
        {
            using (IItemService pService = Factory.GetInstance<IItemService>())
            {
                pService.AddItemsViewCount(id);
                var project = new ProjectInfoConverter()
                    .Convert(pService.GetItems(id));
                return PartialView("ProjectInfoControl", project);
            }

        }

        [Authorize]
        public ActionResult Message(string id)
        {
            using (IMessageService pService = Factory.GetInstance<IMessageService>())
            {
                if (string.IsNullOrWhiteSpace(id))
                {
                    return View(pService.GetMessageList());

                }
                else
                {
                    return View(pService.GetMessageList(id));
                }
            }
           
        }
    }
}
